dojo.provide("xray.Socket");

dojo.declare(
	"xray.Socket",
	null,
	{
		constructor:function(){
			this.isConnected = false;
			this.socket;
			this.socketInterval;
		},
		
		disconnect:function(){
			this.isConnected = false;
			dojo.publish("socket/disconnected");
			
			if (!this.socketInterval){
				// retry connecting after every x miliseconds
				this.socketInterval = setInterval(dojo.hitch(this, function(){
					if (this.eventData){
						this.socket.removeEventListener(air.ProgressEvent.SOCKET_DATA, dojo.hitch(this, "handleData"));
						this.eventData = null;
					}
					if (this.eventClose){
						this.socket.removeEventListener(air.Event.CLOSE, dojo.hitch(this, "disconnect"));
						this.eventClose = null;
					}
					if (this.eventIO){
						this.socket.removeEventListener(air.IOErrorEvent.IO_ERROR, dojo.hitch(this, "disconnect"));
						this.eventIO = null;
					}
					if (this.eventStream){
						this.socket.removeEventListener(air.IOErrorEvent.STREAM_ERROR, dojo.hitch(this, "disconnect"));
						this.eventIO = null;
					}
					if (this.eventConnect){
						this.socket.removeEventListener(air.Event.CONNECT, dojo.hitch(this, "connected"));
						this.eventConnect = null;
					}
					if (!this.isConnected){
						this.connect();
					}
				}), 5000);	
			}
		},
		
		connected:function(){
			if (this.socketInterval){
				clearInterval(this.socketInterval);
				this.socketInterval = null;
			}
			this.isConnected = true;
			
			// publish event for other modules to hook in
			dojo.publish("socket/connected");
			
			this.eventData = this.socket.addEventListener(air.ProgressEvent.SOCKET_DATA, dojo.hitch(this, "handleData"));
			this.eventClose = this.socket.addEventListener(air.Event.CLOSE, dojo.hitch(this, "disconnect"));
		},
		
		connect:function(){
			this.socket = new air.Socket("localhost", 56789);
			this.eventConnect = this.socket.addEventListener(air.Event.CONNECT, dojo.hitch(this, "connected"));
			this.eventIO = this.socket.addEventListener(air.IOErrorEvent.IO_ERROR, dojo.hitch(this, "disconnect"));
		},
		
		getData:function(){
			return this.socket.readUTFBytes(this.socket.bytesAvailable);
		},
		
		handleData:function(){
			// For connecting/overriding.
		}
	}
);